<template>
  <van-nav-bar
    title="收货地址"
    left-text="返回"
    left-arrow
    @click-left="$router.back()"
  />

  <van-address-list
    v-if="cities"
    v-model="chosenAddressId"
    :list="cities"
    default-tag-text="默认"
    @add="onAdd"
    @edit="onEdit"
    @click-item="onClick"
  />
</template>

<script setup lang="ts">
import { useAddressStore } from '@/stores/address'
import { useContentStore } from '@/stores/content'
import { showToast } from 'vant'
const conent = useContentStore()
const address = useAddressStore()
//获取地址数据
address.getCities(conent.token as string)

//默认id
const defaultId = ref('1')

//选中id
const chosenAddressId = ref('2')

const item =  localStorage.getItem('address')
if (item) {
  
  chosenAddressId.value = JSON.parse(item)[0].id
}


//渲染数据列表
const cities = computed(() => {
  if (address?.cities) {
    return address.cities.map((item) => {
      return {
        id: item.id,
        name: item.name,
        tel: item.phone,
        address: item.area + item.address,
        isDefault: item.id === defaultId.value
      }
    })
  }
  return
})

//点击新增按钮
const onAdd = () => showToast('没地址新增了')
// @ts-ignore
const onEdit = (item: any, index: any) => {
  item
  index
  showToast('默认地址切换开发中')
}

//点击任意地址触发
function onClick(item: any, index: number) {
  chosenAddressId.value = index + 1 + ''
  //修改仓库
  address.selectedId(chosenAddressId.value)

  //存存本地
  localStorage.setItem('address', JSON.stringify(address.selectedId(chosenAddressId.value)))
}
</script>
